const router = require('koa-router')();  //注意：引入的方式
const db = require('../utils/database.js')

router.prefix('/table-cut')

router.get('/', ctx => {
    ctx.body = "table-cut--index";
})


// 查询 分页 搜索 排序
router.get('/list', async ctx => {
    const { order, by, page = 0, pageSize = 20, query } = ctx.request.query // request可省略
    let sort = {}, where = {}
    if (by) {
        sort[by] = order // by是条件 order是-1或1
    }
    if (query) {
        where.cut = { $regex: new RegExp(query) }
    }
    const data = await db.find('table-cut', { where, sort, skip: page * pageSize, limit: pageSize })
    ctx.body = { success: true, code: 20000, message: "数据查询成功", data }
})

// 新增
router.post('/save', async ctx => {
    const { cut, min, max } = ctx.request.body;
    const data = await db.insert('table-cut', { cut, min, max })
    ctx.body = { success: true, code: 20000, message: "数据新增成功", data }
		
})

// 修改
router.post('/modify', async ctx => {
    const { _id, cut, min, max } = ctx.request.body
    const data = await db.update('table-cut', { _id }, { cut, min, max })
    ctx.body = { success: true, code: 20000, message: "数据修改成功", data }
})

// 删除
router.get('/delete', async ctx => {
    const { _id } = ctx.request.query
    const data = await db.delete('table-cut', { _id })
    ctx.body = { success: true, code: 20000, message: "数据删除成功", data }
})

module.exports = router
